import os
from os import listdir
from .recorder import Recorder
from .utils import load_json, desktop_dir, get_path, ignore_key, standby_key


class Projector:
    """
    
    Contains desktop organisation helper functions
    
    """

    def __init__(self, extensions):

        """
        Obtains various localised information about the platform and user, and performs system checks upon initialization.
        """

        # References:   https://en.wikipedia.org/wiki/Environment_variable
        # Default_values
        #               https://en.wikipedia.org/wiki/Windows_NT#Releases
        self.extensions = extensions

    def project_folder(self, item, recorder):
        if item not in self.extensions and "Folders" in self.extensions:
            recorder.add("Folders", item)

    def project_file(self, item, recorder):
        ext = os.path.splitext(item)[1].lower()
        for folder, extensions in self.extensions.items():
            if ext in extensions:
                recorder.add(folder, item)
                return
        print("[Extension not found]", item)
        recorder.add(standby_key, item)

    def check_ignore(self, item):
        for val in self.extensions[ignore_key]:
            if item.endswith(val):
                return True
        return False

    def project(self):

        """
        This function gets two lists with all the things on the desktops
        and copies them into their respective folders
        """

        # image extensions source: https://fileinfo.com/filetypes/raster_image,
        #                          https://fileinfo.com/filetypes/vector_image,
        #                          https://fileinfo.com/filetypes/camera_raw
        # music extensions source: https://fileinfo.com/filetypes/audio
        # movie extensions source: http://bit.ly/2wvYjyr
        # text extensions source:  http://bit.ly/2wwcfZs

        recorder = Recorder()

        def condition(x):
            return (
                x not in self.extensions
                and not (x.startswith(".") or x.startswith(".."))
                and not self.check_ignore(x)
            )

        items = sorted(filter(condition, listdir(desktop_dir)))

        for item in items:
            folder = get_path(item)
            if os.path.isdir(folder):
                self.project_folder(item, recorder)
            else:
                self.project_file(item, recorder)
        return recorder
